package service

import (
	"devops/middleware"
	"devops/models"
	"fmt"
	"strconv"
)

type EventType string

const (
	ProjectCreate = "ProjectCreate"
	ProjectUpdate = "ProjectUpdate"
	ProjectDelete = "ProjectDelete"

	CiCreate = "CiCreate"
	CiUpdate = "CiUpdate"
	CiDelete = "CiDelete"

	BuildRun      = "BuildRun"
	BuildTimerRun = "BuildTimerRun"
	BuildStop     = "BuildStop"
	BuildDelete   = "BuildDelete"
	BuildSuccess  = "BuildSuccess"
	BuildFail     = "BuildFail"
	BuildAborted  = "BuildAborted"
)

var EventMsg = map[EventType]string{
	ProjectCreate: "新建了项目",
	ProjectUpdate: "更新了项目信息",
	ProjectDelete: "删除了项目",

	CiCreate: "开启了持续集成",
	CiUpdate: "更新了持续集成",
	CiDelete: "删除了持续集成",

	BuildRun:     "触发了持续集成 %s, 任务 %d",
	BuildTimerRun:"定时触发了持续集成 %s, 任务 %d",
	BuildStop:    "中止了持续集成 %s, 任务 %d",
	BuildDelete:  "删除了持续集成 %s 的任务 %d",
	BuildSuccess: "持续集成 %s, 任务 %d, 构建成功",
	BuildFail:    "持续集成 %s, 任务 %d, 构建失败",

}

func (d *devOps) GetAllEventTimeBetween(startTime int, endTime int) []models.Event {
	return models.GetAllEventTimeBetween(startTime, endTime)
}


func (d *devOps) ProjectEvent(typ EventType, user *middleware.User, project models.Project) {
	user = checkUser(user)
	uid, _ := strconv.Atoi(user.UserID)
	e := models.Event{
		Uid: uid,
		Username:user.UserName,
		Action: string(typ),
		ActionMsg: EventMsg[typ] + project.Name,
		ProjectId: project.ID,
	}
	models.CreateEvent(e)
}


func (d *devOps) CiEvent(typ EventType, user *middleware.User, ci models.CI) {
	user = checkUser(user)
	uid, _ := strconv.Atoi(user.UserID)
	e := models.Event{
		Uid: uid,
		Username:user.UserName,
		Action: string(typ),
		ActionMsg: EventMsg[typ] + ci.Name,
		ProjectId: ci.ProjectId,
		CId: ci.ID,
	}
	models.CreateEvent(e)
}


func (d *devOps) BuildEvent(typ EventType, user *middleware.User, build models.Build) {
	user = checkUser(user)
	uid, _ := strconv.Atoi(user.UserID)
	ci := models.GetCIByID(build.CID)
	if ci == nil {
		return
	}
	e := models.Event{
		Uid: uid,
		Username:user.UserName,
		Action: string(typ),
		ActionMsg: fmt.Sprintf(EventMsg[typ], ci.Name, build.Number),
		ProjectId: ci.ProjectId,
		CId: build.CID,
		BuildId: build.ID,
	}
	models.CreateEvent(e)
}

func(d *devOps) SyncCiBuildEvent() {
	events := models.GetAllCiEvents()
	for _, e := range events {
		ci := models.GetCIByID(e.CId)
		if ci == nil {
			continue
		}
		project := models.GetProjectByID(ci.ProjectId)
		if project.ID == 0 {
			continue
		}
		d.SyncCiBuild(*ci, project.Name)
	}
}

// ========================================================
func checkUser(user *middleware.User) *middleware.User {
	if user == nil {
		user = &middleware.User{UserID: "0", UserName: "项目助手"}
	}
	return user
}